package praca.framework;

import java.io.IOException;

import javax.microedition.khronos.opengles.GL10;

import praca.interfejsy.FileIO;
import praca.interfejsy.Game;
import praca.interfejsy.Texture;
import android.graphics.Bitmap;
import android.opengl.GLUtils;
import android.util.Log;

public class TextureGL implements Texture{
	private int textureId;
	GL10 gl;
	FileIO io;
	Game game;
	String textureName;
	
	private TextureGL(Game gr, Bitmap bitmap){
		game = gr;
		gl=game.getGraphics().getGl();
		if(gl == null)
			Log.d("test", "Null jest :(");
		Log.d("test", "Texture konstruktor");
		io = gr.getFileIO();
		loadTexture(bitmap);
	}
	
	public TextureGL(Game gr, String bitmapName){
		game = gr;
		gl=game.getGraphics().getGl();
		if(gl == null)
			Log.d("test", "Null jest :(");
		Log.d("test", "Texture konstruktor");
		io = gr.getFileIO();
		loadTexture(bitmapName);
	}
	
	
	private void loadTexture(Bitmap bitmap) {
		Log.d("test", "Rysuje");
		int textureIds[] = new int[1];
		gl.glGenTextures(1, textureIds, 0);
		textureId = textureIds[0];
		gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
		GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);
		bitmap.recycle();
	}

	private void loadTexture(String bitmapName) {
		textureName = bitmapName;
		Bitmap bitmap;
		try {
			bitmap = io.loadBitmap(bitmapName);
		} catch (IOException e) {
			throw new RuntimeException();
		}
		int textureIds[] = new int[1];
		gl.glGenTextures(1, textureIds, 0);
		textureId = textureIds[0];
		gl.glEnable(GL10.GL_TEXTURE_2D);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
		GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);
		bitmap.recycle();
		
		
		
	}

	public void reload(){
		loadTexture(textureName);
	}
	@Override
	public void disposeTexture() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public int getTextureId() {
		return textureId;
	}
	
	
}
